<template>
  <view class="container">
    <!-- 搜索筛选区域 -->
    <view class="search-container">
      <view class="search-filters">
        <!-- 申请年月选择 -->
        <view class="date-filter">
          <text class="filter-label">申请年月:</text>
          <view class="date-picker" @click="showDatePicker">
            <text>{{ searchYearMonth || '请选择年月' }}</text>
            <text class="arrow-icon">▼</text>
          </view>
        </view>

        <!-- 状态筛选 -->
        <view class="status-filter">
          <text class="filter-label">审批状态:</text>
          <view class="status-select" @click="showStatusPicker">
            <text>{{ getStatusText(searchStatus) }}</text>
            <text class="arrow-icon">▼</text>
          </view>
        </view>
      </view>
    </view>

    <!-- 年月选择弹窗 -->
    <view class="date-picker-modal" v-if="showDateModal">
      <view class="modal-content">
        <view class="modal-header">
          <text class="modal-title">选择年月</text>
          <view class="modal-actions">
            <text class="cancel-btn" @click="hideDatePicker">取消</text>
            <text class="confirm-btn" @click="confirmDate">确定</text>
          </view>
        </view>
        <view class="date-picker-body">
          <!-- 这里是年月选择组件，实际项目中需要替换为真实的选择器 -->
          <view class="date-demo">
            <text>年月选择器示例</text>
            <text class="demo-text">2025年05月</text>
            <view class="demo-calendar">
              <view class="year-month-selector">
                <button @click="changeYear(-1)">上一年</button>
                <text>{{ selectedYear }}年</text>
                <button @click="changeYear(1)">下一年</button>
              </view>
              <view class="month-grid">
                <button v-for="month in 12" :key="month"
                        :class="{ 'selected': month === selectedMonth }"
                        @click="selectMonth(month)">{{ month }}月</button>
              </view>
            </view>
          </view>
        </view>
      </view>
    </view>

    <!-- 状态选择弹窗 -->
    <view class="status-picker-modal" v-if="showStatusModal">
      <view class="modal-content">
        <view class="modal-header">
          <text class="modal-title">选择状态</text>
          <text class="close-btn" @click="hideStatusPicker">×</text>
        </view>
        <view class="status-items">
          <view
              class="status-item"
              :class="{ 'active': searchStatus === statusKey }"
              v-for="(statusText, statusKey) in statusOptions"
              :key="statusKey"
              @click="selectStatus(statusKey)">
            <text>{{ statusText }}</text>
          </view>
        </view>
      </view>
    </view>

    <!-- 加载遮罩 -->
    <view class="loading-mask" v-if="loading">
      <view class="loading-content">
        <text class="loading-text">正在处理...</text>
      </view>
    </view>

    <!-- 无数据提示 -->
    <view v-if="!loading && leaveList.length === 0" class="empty-list">
      <text class="empty-icon">📄</text>
      <text class="empty-text">暂无符合条件的请假申请</text>
    </view>

    <!-- 请假列表 -->
    <view v-else class="leave-list">
      <view v-for="(item, index) in leaveList" :key="item.id" class="leave-card">
        <view class="card-header">
          <text class="employee-name">{{ item.staffName || '未知员工' }}</text>
          <text class="leave-type">{{ getLeaveTypeText(item.leaveTypeId) }}</text>
          <text class="status-tag" :class="getStatusClass(item.status)">{{ getStatusText(item.status) }}</text>
        </view>

        <view class="card-body">
          <view class="leave-dates">
            <text class="label">请假日期:</text>
            <text class="value">{{ formatDateRange(item.startDate, item.endDate, item.startPeriod, item.endPeriod) }}</text>
          </view>

          <view class="leave-duration">
            <text class="label">请假时长:</text>
            <text class="value">{{ item.workingDays || '未知' }}天</text>
          </view>

          <view class="leave-reason">
            <text class="label">请假原因:</text>
            <text class="value">{{ item.reason || '无' }}</text>
          </view>
        </view>

        <view class="card-footer">
          <view class="footer-content">
            <text class="apply-time">申请时间: {{ formatDateTime(item.createdAt) }}</text>

            <!-- 操作按钮 -->
            <view class="action-buttons" v-if="item.status === 'PENDING'">
              <button
                  class="reject-btn"
                  @click="handleReject(item)">
                拒绝
              </button>
              <button
                  class="approve-btn"
                  @click="approveLeave(item)">
                批准
              </button>
            </view>
          </view>
        </view>
      </view>
    </view>

    <!-- 拒绝原因弹窗 -->
    <view class="modal-mask" v-if="showRejectModal">
      <view class="modal-container">
        <view class="modal-header">
          <text class="modal-title">拒绝申请</text>
          <text class="close-btn" @click="closeRejectModal">×</text>
        </view>

        <view class="modal-body">
          <view class="reject-info">
            <text class="reject-employee">
              申请人: {{ currentRejectItem.staffName || '未知员工' }}
            </text>
            <text class="reject-type">
              {{ getLeaveTypeText(currentRejectItem.leaveTypeId) }} · {{ formatDateRange(currentRejectItem.startDate, currentRejectItem.endDate, currentRejectItem.startPeriod, currentRejectItem.endPeriod) }}
            </text>
          </view>

          <textarea
              class="reason-input"
              v-model="rejectReason"
              placeholder="请输入拒绝原因"
              maxlength="200"
              auto-focus></textarea>
          <text class="char-count">{{ rejectReason.length }}/200</text>
        </view>

        <view class="modal-footer">
          <button class="cancel-btn" @click="closeRejectModal">取消</button>
          <button class="confirm-btn" @click="submitReject(currentRejectItem)">确认</button>
        </view>
      </view>
    </view>
  </view>
</template>

<script>
export default {
  data() {
    const now = new Date();
    return {
      leaveList: [],
      loading: false,
      showRejectModal: false,
      currentRejectIndex: -1,
      currentRejectItem: {},
      rejectReason: '',
      isUniAppEnv: typeof uni !== 'undefined',

      // 搜索筛选相关
      searchYearMonth: `${now.getFullYear()}-${(now.getMonth() + 1).toString().padStart(2, '0')}`,
      searchStatus: '',
      showDateModal: false,
      showStatusModal: false,
      selectedYear: now.getFullYear(),
      selectedMonth: now.getMonth() + 1,

      // 状态选项
      statusOptions: {
        '': '全部',
        'PENDING': '待审批',
        'APPROVED': '已批准',
        'REJECTED': '已拒绝',
        'CANCELLED': '已取消'
      }
    }
  },
  computed: {
    // 请假类型样式
    leaveTypeStyles() {
      return {
        1: { bgColor: '#1890ff', textColor: '#fff' },
        2: { bgColor: '#722ed1', textColor: '#fff' },
        3: { bgColor: '#fa8c16', textColor: '#fff' },
        4: { bgColor: '#52c41a', textColor: '#fff' }
      }
    }
  },
  onLoad() {
    this.loadLeaveList();
  },
  methods: {
    // 加载请假列表
    loadLeaveList() {
      this.loading = true;
      this.req({
        url: '/leave/applications/list',
        method: 'POST',
        data: {
          startDate:  this.searchYearMonth + '-01',
          status: this.searchStatus
        }
      }).then(res => {
        this.leaveList  = res.rows
        this.loading = false
      })
    },

    // 获取请假类型文本
    getLeaveTypeText(typeId) {
      const leaveTypes = ['未知类型', '全薪事假', '无薪事假'];
      return leaveTypes[typeId] || '未知类型';
    },

    // 获取状态文本
    getStatusText(status) {
      return this.statusOptions[status] || '未知状态';
    },

    // 获取状态样式类
    getStatusClass(status) {
      switch(status) {
        case 'PENDING': return 'status-pending';
        case 'APPROVED': return 'status-approved';
        case 'REJECTED': return 'status-rejected';
        case 'CANCELLED': return 'status-cancelled';
        default: return '';
      }
    },

    // 格式化日期范围（考虑时段）
    formatDateRange(startDate, endDate, startPeriod, endPeriod) {
      if (!startDate || !endDate) return '';

      // 假设日期格式为YYYY-MM-DD
      const start = startDate.split('-');
      const end = endDate.split('-');

      // 格式化时段
      const formatPeriod = (period) => {
        switch(period) {
          case 'MORNING': return '上午';
          case 'AFTERNOON': return '下午';
          case 'WHOLE_DAY': return '全天';
          default: return '';
        }
      };

      const startPeriodText = formatPeriod(startPeriod);
      const endPeriodText = formatPeriod(endPeriod);

      // 如果是同一年，省略结束年份
      if (start[0] === end[0]) {
        if (startDate === endDate) {
          return `${start[1]}月${start[2]}日 ${startPeriodText}~${endPeriodText}`;
        }
        return `${start[1]}月${start[2]}日${startPeriodText} - ${end[1]}月${end[2]}日${endPeriodText}`;
      }

      return `${start[0]}年${start[1]}月${start[2]}日${startPeriodText} - ${end[0]}年${end[1]}月${end[2]}日${endPeriodText}`;
    },

    // 格式化日期时间
    formatDateTime(dateTime) {
      if (!dateTime) return '';

      // 假设格式为YYYY-MM-DD HH:MM:SS
      return dateTime.replace(' ', ' ');
    },

    // 处理拒绝按钮点击
    handleReject(item) {
      // this.currentRejectIndex = index;
      this.currentRejectItem = item
      this.rejectReason = '';
      this.showRejectModal = true;
    },

    // 关闭拒绝原因弹窗
    closeRejectModal() {
      this.showRejectModal = false;
      this.currentRejectIndex = -1;
      this.currentRejectItem = {};
      this.rejectReason = '';
    },

    // 通过请假申请
    approveLeave(item) {
      if (this.loading) return;
      uni.showModal({
        title: '确认通过',
        content: `确定要批准 ${item.staffName} 的${this.getLeaveTypeText(item.leaveTypeId)}申请吗？`,
        confirmText: '确认',
        cancelText: '取消',
        success: (res) => {
          if (res.confirm) {
            this.loading = true;
            const applyLeaveFrom = {
              id: item.id,
              status: 'APPROVED'
            };
            this.req({
              url: '/leave/applications/audit',
              method: 'POST',
              data: applyLeaveFrom
            }).then(res => {
              uni.showToast({
                title: '审批通过成功',
                icon: 'success'
              });
              this.loading = false;
              this.loadLeaveList();
            })
          }
        }
      });
    },

    // 拒绝请假申请
    submitReject(item) {
      if (this.loading) return;

      // 验证拒绝原因
      if (!this.rejectReason.trim()) {
        uni.showToast({
          title: '请输入拒绝原因',
          icon: 'none'
        });
        return;
      }

      this.loading = true;
      const applyLeaveFrom = {
        id: item.id,
        status: 'REJECTED',
        approvalReason:  this.rejectReason
      };
      this.req({
        url: '/leave/applications/audit',
        method: 'POST',
        data: applyLeaveFrom
      }).then(res => {
        uni.showToast({
          title: '已拒绝申请',
          icon: 'success'
        });
        this.loading = false;
        this.showRejectModal = false;
        this.loadLeaveList();
      })

    },

    // 显示日期选择器
    showDatePicker() {
      this.showDateModal = true;
    },

    // 隐藏日期选择器
    hideDatePicker() {
      this.showDateModal = false;
    },

    // 确认日期选择
    confirmDate() {
      this.searchYearMonth = `${this.selectedYear}-${this.selectedMonth.toString().padStart(2, '0')}`;
      this.req({
        url: '/leave/applications/list',
        method: 'POST',
        data: {
          startDate:  this.searchYearMonth + '-01',
          status: this.searchStatus
        }
      }).then(res => {
        this.leaveList  = res.rows
      })
      this.showDateModal = false;
    },

    // 改变年份
    changeYear(delta) {
      this.selectedYear += delta;
    },

    // 选择月份
    selectMonth(month) {
      this.selectedMonth = month;
    },

    // 显示状态选择器
    showStatusPicker() {
      this.showStatusModal = true;
    },

    // 隐藏状态选择器
    hideStatusPicker() {
      this.showStatusModal = false;
    },

    // 选择状态
    selectStatus(status) {
      this.searchStatus = status;
      this.req({
        url: '/leave/applications/list',
        method: 'POST',
        data: {
          startDate:  this.searchYearMonth + '-01',
          status: this.searchStatus
        }
      }).then(res => {
        this.leaveList  = res.rows
      })
      this.showStatusModal = false;
    }
  }
}
</script>

<style>
/* 样式保持不变 */
.container {
  padding: 30rpx;
  background-color: #f8f8f8;
  min-height: 100vh;
}

.page-header {
  padding: 20rpx 0;
  border-bottom: 1rpx solid #eee;
}

.page-title {
  font-size: 36rpx;
  font-weight: bold;
  color: #333;
  text-align: center;
}

/* 搜索区域样式 */
.search-container {
  background-color: #fff;
  border-radius: 12rpx;
  padding: 20rpx 30rpx;
  margin-top: 20rpx;
  box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.05);
}

.search-filters {
  display: flex;
  flex-wrap: wrap;
  gap: 20rpx;
}

.date-filter, .status-filter {
  display: flex;
  align-items: center;
  width: 100%;
}

.filter-label {
  font-size: 26rpx;
  color: #666;
  width: 120rpx;
}

.date-range {
  flex: 1;
  display: flex;
  align-items: center;
}

.date-picker {
  flex: 1;
  height: 70rpx;
  line-height: 70rpx;
  border: 1rpx solid #eee;
  border-radius: 10rpx;
  padding: 0 20rpx;
  font-size: 26rpx;
  color: #333;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.date-picker text {
  color: #999;
}

.date-picker text:first-child {
  color: #333;
}

.separator {
  padding: 0 10rpx;
  color: #999;
}

.status-select {
  flex: 1;
  height: 70rpx;
  line-height: 70rpx;
  border: 1rpx solid #eee;
  border-radius: 10rpx;
  padding: 0 20rpx;
  font-size: 26rpx;
  color: #333;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.search-buttons {
  display: flex;
  justify-content: center;
  margin-top: 20rpx;
  gap: 30rpx;
}

.search-btn {
  width: 200rpx;
  height: 80rpx;
  line-height: 80rpx;
  border-radius: 40rpx;
  font-size: 28rpx;
  border: none;
  background-color: #1890ff;
  color: #fff;
  display: flex;
  justify-content: center;
  align-items: center;
}

.search-icon {
  margin-right: 10rpx;
}

/* 日期选择器弹窗 */
.date-picker-modal {
  position: fixed;
  bottom: 0;
  left: 0;
  width: 100%;
  background-color: #f8f8f8;
  z-index: 999;
  border-radius: 20rpx 20rpx 0 0;
  transform: translateY(100%);
  animation: slide-up 0.3s ease-out forwards;
}

@keyframes slide-up {
  from {
    transform: translateY(100%);
  }
  to {
    transform: translateY(0);
  }
}

.modal-content {
  padding: 30rpx 40rpx;
}

.modal-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding-bottom: 20rpx;
  border-bottom: 1rpx solid #eee;
}

.modal-title {
  font-size: 32rpx;
  font-weight: 500;
  color: #333;
}

.modal-actions {
  display: flex;
  gap: 30rpx;
}

.cancel-btn, .confirm-btn {
  font-size: 28rpx;
  color: #1890ff;
}

.date-picker-body {
  padding-top: 20rpx;
}

.date-demo {
  text-align: center;
  padding: 30rpx 0;
}

.demo-text {
  font-size: 32rpx;
  color: #333;
  display: block;
  margin-bottom: 20rpx;
}

.demo-calendar {
  padding: 20rpx;
  border-radius: 12rpx;
}

.year-month-selector {
  display: flex;
  justify-content: center;
  align-items: center;
  margin-bottom: 20rpx;
}

.year-month-selector button {
  padding: 10rpx 20rpx;
  margin: 0 20rpx;
  background-color: #f5f5f5;
  border-radius: 10rpx;
}

.month-grid {
  display: grid;
  grid-template-columns: repeat(4, 1fr);
  gap: 15rpx;
}

.month-grid button {
  height: 60rpx;
  line-height: 60rpx;
  background-color: #fff;
  border: 1rpx solid #eee;
  border-radius: 10rpx;
}

.month-grid button.selected {
  background-color: #1890ff;
  color: #fff;
}

/* 状态选择弹窗 */
.status-picker-modal {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 999;
}

.status-picker-modal .modal-content {
  background-color: #fff;
  width: 80%;
  max-width: 600rpx;
  border-radius: 20rpx;
  overflow: hidden;
}

.status-picker-modal .modal-header {
  padding: 20rpx 30rpx;
}

.status-items {
  max-height: 400rpx;
  overflow-y: auto;
}

.status-item {
  padding: 20rpx 30rpx;
  font-size: 28rpx;
  color: #333;
  border-bottom: 1rpx solid #eee;
}

.status-item.active {
  background-color: #f5f5f5;
  color: #1890ff;
}

.leave-list {
  margin-top: 20rpx;
}

.leave-card {
  background-color: #fff;
  border-radius: 12rpx;
  margin-bottom: 20rpx;
  box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.05);
  overflow: hidden;
}

.card-header {
  padding: 20rpx 30rpx;
  border-bottom: 1rpx solid #eee;
  display: flex;
  justify-content: space-between;
  align-items: center;
  flex-wrap: wrap;
}

.employee-name {
  font-size: 32rpx;
  font-weight: 500;
  color: #333;
}

.leave-type {
  font-size: 24rpx;
  color: #fff;
  padding: 6rpx 12rpx;
  border-radius: 6rpx;
}

.status-tag {
  font-size: 24rpx;
  padding: 6rpx 12rpx;
  border-radius: 6rpx;
  margin-left: 10rpx;
}

.status-pending {
  background-color: #fff7e6;
  color: #fa8c16;
}

.status-approved {
  background-color: #f6ffed;
  color: #52c41a;
}

.status-rejected {
  background-color: #fff1f0;
  color: #ff4d4f;
}

.status-cancelled {
  background-color: #f5f5f5;
  color: #8c8c8c;
}

.card-body {
  padding: 20rpx 30rpx;
}

.leave-dates, .leave-duration, .leave-reason {
  display: flex;
  margin-bottom: 16rpx;
}

.label {
  font-size: 26rpx;
  color: #666;
  width: 180rpx;
}

.value {
  font-size: 26rpx;
  color: #333;
  flex: 1;
}

.card-footer {
  padding: 20rpx 30rpx;
}

.footer-content {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.apply-time {
  font-size: 24rpx;
  color: #888;
  max-width: 60%;
}

/* 优化后的按钮样式 */
.action-buttons {
  display: flex;
  gap: 10rpx;
}

.reject-btn, .approve-btn {
  width: 140rpx;
  height: 64rpx;
  line-height: 64rpx;
  border-radius: 32rpx;
  font-size: 26rpx;
  border: none;
}

.reject-btn {
  background-color: #ff4d4f;
  color: #fff;
}

.approve-btn {
  background-color: #1890ff;
  color: #fff;
}

.empty-list {
  padding: 100rpx 0;
  display: flex;
  flex-direction: column;
  align-items: center;
}

.empty-icon {
  font-size: 100rpx;
  color: #ccc;
  margin-bottom: 20rpx;
}

.empty-text {
  font-size: 30rpx;
  color: #999;
}

.modal-mask {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 999;
}

.modal-container {
  background-color: #fff;
  width: 86%;
  max-width: 680rpx;
  border-radius: 20rpx;
  overflow: hidden;
  transform: scale(0.95);
  animation: modal-scale 0.2s ease-out forwards;
}

@keyframes modal-scale {
  from {
    transform: scale(0.95);
    opacity: 0.8;
  }
  to {
    transform: scale(1);
    opacity: 1;
  }
}

.modal-header {
  padding: 30rpx 40rpx;
  border-bottom: 1rpx solid #eee;
  display: flex;
  justify-content: space-between;
  align-items: center;
  position: relative;
}

.modal-title {
  font-size: 34rpx;
  font-weight: 500;
  color: #333;
}

.close-btn {
  font-size: 40rpx;
  color: #999;
  position: absolute;
  right: 30rpx;
  top: 26rpx;
}

.modal-body {
  padding: 30rpx 40rpx;
}

.reject-info {
  margin-bottom: 20rpx;
  padding-bottom: 20rpx;
  border-bottom: 1rpx solid #eee;
}

.reject-employee {
  font-size: 28rpx;
  color: #333;
  display: block;
  margin-bottom: 10rpx;
}

.reject-type {
  font-size: 26rpx;
  color: #666;
  display: block;
}

.reason-input {
  width: 100%;
  min-height: 220rpx;
  border: 1rpx solid #eee;
  border-radius: 12rpx;
  padding: 20rpx;
  font-size: 28rpx;
  box-sizing: border-box;
  line-height: 1.5;
}

.char-count {
  display: block;
  text-align: right;
  font-size: 24rpx;
  color: #888;
  margin-top: 10rpx;
}

.modal-footer {
  display: flex;
  border-top: 1rpx solid #eee;
}

.cancel-btn, .confirm-btn {
  flex: 1;
  height: 90rpx;
  line-height: 90rpx;
  text-align: center;
  font-size: 32rpx;
}

.cancel-btn {
  color: #666;
}

.confirm-btn {
  color: #1890ff;
  font-weight: 500;
}

.loading-mask {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 999;
}

.loading-content {
  background-color: #fff;
  padding: 40rpx 60rpx;
  border-radius: 12rpx;
  display: flex;
  flex-direction: column;
  align-items: center;
}

.loading-text {
  font-size: 28rpx;
  color: #333;
  margin-top: 20rpx;
}
</style>